package logic

import (
	"context"
	"fmt"
	"user_srv/models"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	// todo: add your logic here and delete this line
	users := models.User{
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	models.DB.Where("phone=?", in.Phone).Find(&users)
	if users.ID == 0 {
		models.DB.Debug().Create(&users)
		return nil, fmt.Errorf("用户不存在,自动注册")
	}
	if users.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新登陆")
	}

	return &user.LoginResponse{
		Id: int64(users.ID),
	}, nil
}
